﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
//using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using QuanLyKho.Common;
using QuanLyKho.DataAccess;
using QuanLyKho.GUI.Library;
using System.Threading;
using System.Data.SqlClient;
namespace QuanLyKho.GUI
{
    public partial class frmLogin : Form
    {
        clsLibrary clsMD5 = new clsLibrary();
        static public string tentaikhoan = "";
        static public long userID = 0;
        static public bool isAdmin = false;
        bool flag_login = false;
        static public string tenmaychu = new clsConnect().ServerName;
        static public string dbName = new clsConnect().DbName;

        private BackgroundWorker BgWorker_conn;
        private BackgroundWorker BgWorker;
        public frmLogin()
        {
            Control.CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();
            CheckConnection();

            isAdmin = false;
        }
        //ham luu thong tin dang nhap

        public void SaveinfoLog(string _server, string _user, string _pass, string _status)
        {
            XmlTextWriter xtw = new XmlTextWriter("C:\\database\\savelog.xml", null);
            xtw.Formatting = Formatting.Indented;
            xtw.WriteStartDocument();
            xtw.WriteStartElement("AdLogin");
            xtw.WriteElementString("Server", clsMD5.EnCrypt(_server.Trim(), "Havitel"));
            xtw.WriteElementString("Username", clsMD5.EnCrypt(_user.Trim(), "Havitel"));
            xtw.WriteElementString("Password", clsMD5.EnCrypt(_pass.Trim(), "Havitel"));
            xtw.WriteElementString("status", _status);
            xtw.WriteEndElement();
            xtw.WriteEndDocument();
            xtw.Flush();
            xtw.Close();


        }
        //readLogin

        public void readlog()
        {


            XmlDocument doc = new XmlDocument();
            doc.Load("C:\\database\\savelog.xml");
            XmlNode root = doc.DocumentElement;

            if (root.SelectSingleNode("status").InnerText == "True")
            {
                cboSave.Checked = true;
                txtserver.Text = clsMD5.DeCrypt(root.SelectSingleNode("Server").InnerText.Trim(), "Havitel");
                txtTaiKhoan.Text = clsMD5.DeCrypt(root.SelectSingleNode("Username").InnerText.Trim(), "Havitel");
                txtMatKhau.Text = clsMD5.DeCrypt(root.SelectSingleNode("Password").InnerText.Trim(), "Havitel");
            }

        }
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (cboSave.Checked == true)
                {
                    SaveinfoLog(txtserver.Text, txtTaiKhoan.Text, txtMatKhau.Text, cboSave.Checked.ToString());
                }
                else
                {
                    SaveinfoLog("", "", "", "");
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                funcLogin();
            }
        }

        private void funcLogin()
        {
            pnLoading.Visible = true;
            pictureBox1.Visible = false;
            tentaikhoan = txtTaiKhoan.Text;
            string matkhau = txtMatKhau.Text;

            if (txtserver.Text.Length < 1)
            {
                txtserver.Focus();
                lblTitile.Text = "Hãy nhập tên máy chủ !";
            }
            if (tentaikhoan.Length < 1)
            {
                txtTaiKhoan.Focus();
                lblTitile.Text = "Hãy nhập tên tài khoản !";
                return;
            }

            if (matkhau.Length < 1)
            {
                txtMatKhau.Focus();
                lblTitile.Text = "Hãy nhập mật khẩu đăng nhập !";
                return;
            }

            BgWorker = new BackgroundWorker();
            BgWorker.RunWorkerAsync();
            BgWorker.DoWork += new DoWorkEventHandler(BgWorker_DoWork);
            BgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(BgWorker_RunWorkerCompleted);
        }

        void BgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            //pnLoading.Visible = false;
            BgWorker.Dispose();
        }

        void BgWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                lblTitile.Text = "Đang đăng nhập tài khoản...";

                if (tenmaychu.Equals(txtserver.Text) == true)
                {
                    int status = new clsDataAccessUser().UserLogin(tentaikhoan.Trim(), clsMD5.EnCrypt(txtMatKhau.Text.Trim(), "Havitel"));
                    if (status > 0)
                    {
                        isAdmin = new clsDataAccessUser().UserSelectOneWithName(tentaikhoan)[0].Admin;
                        userID = new clsDataAccessUser().UserSelectOneWithName(tentaikhoan)[0].ID;
                        if (status == 2)
                        {
                            lblTitile.Text = "Tài khoản này đã bị khóa. Vui lòng liên hệ với quản trị viên.";
                            return;
                        }
                        Thread thread = new Thread(new ThreadStart(new clsLibrary().runMain));
                        thread.ApartmentState = ApartmentState.STA;
                        thread.Start();
                        this.Close();
                        flag_login = true;
                    }
                    else
                    {
                        lblTitile.Text = "Tài khoản hoặc mật khẩu không đúng. Hãy thử lại!";
                        flag_login = true;
                        return;
                    }
                }
                else
                {
                    lblTitile.Text = "Sai tên máy chủ hãy thử lại. Hãy thử lại!";
                    flag_login = true;
                    return;
                }

            }
            catch (Exception ex)
            {
                lblTitile.Text = "Không thể kết nối máy chủ. Truy cập màn hình kết nối sau 3 giây.";
                flag_login = false;
                Thread.Sleep(3000);
            }
            finally
            {
                if (!flag_login)
                {

                    Thread thread = new Thread(new ThreadStart(new clsLibrary().RunConnect));
                    thread.ApartmentState = ApartmentState.STA;
                    thread.Start();
                    this.Close();
                }
            }
        }

        private void Login_FormClosing(object sender, FormClosingEventArgs e)
        {
            Application.Exit();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void CheckConnection()
        {
            BgWorker_conn = new BackgroundWorker();
            BgWorker_conn.RunWorkerAsync();
            BgWorker_conn.DoWork += new DoWorkEventHandler(BgWorker_conn_DoWork);
            BgWorker_conn.RunWorkerCompleted += new RunWorkerCompletedEventHandler(BgWorker_conn_RunWorkerCompleted);
            pnLoading.Visible = true;
        }

        void BgWorker_conn_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            //throw new NotImplementedException();
            txtMatKhau.Enabled = true;
            txtTaiKhoan.Enabled = true;
            button1.Enabled = true;
            pnLoading.Visible = false;
            BgWorker_conn.Dispose();
        }

        void BgWorker_conn_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                lblTitile.Text = "Đang kiểm tra kết nối. Vui lòng chờ";
                SqlConnection conn = new clsConnect().GetSqlConnection();
                conn.Open();
                lblTitile.Text = "";
                flag_login = true;
            }
            catch (Exception ex)
            {
                lblTitile.Text = "Không thể kết nối máy chủ. Truy cập màn hình kết nối sau 3 giây.";
                Thread.Sleep(3000);
                flag_login = false;
            }
            finally
            {
                if (!flag_login)
                {
                    Thread thread = new Thread(new ThreadStart(new clsLibrary().RunConnect));
                    thread.ApartmentState = ApartmentState.STA;
                    thread.Start();
                    this.Close();
                }
            }
        }



        private void txtMatKhau_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
                funcLogin();
        }

        private void txtTaiKhoan_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
                funcLogin();
        }

        private void frmLogin_Load(object sender, EventArgs e)
        {
            if (!System.IO.File.Exists("C:\\database\\savelog.xml"))
            {
                return;
            }
            else
            {
                readlog();
            }
        }
    }
}
